package com.asiainfo_linkage.runtask;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.TimerTask;
import org.apache.log4j.Logger;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import com.asiainfo_linkage.message.EmailSender;
import com.asiainfo_linkage.message.MessageSender;
import com.asiainfo_linkage.model.AddMember;
import com.asiainfo_linkage.model.RemPlan;
import com.asiainfo_linkage.model.RemTask;
import com.asiainfo_linkage.service.SendService;
@IocBean
public class MyTask extends TimerTask {
	@Inject
	private SendService sendService=new SendService() ;
	
	//private static final Logger logger=Logger.getLogger("mylog");

	List<RemPlan> plans = null;
 	private RemTask remTask;
	
	private List<AddMember> receivers;
	
	public RemTask getRemTask() {
		return remTask;
	}

	public void setRemTask(RemTask remTask) {
		this.remTask = remTask;
	}

	public List<AddMember> getReceivers() {
		return receivers;
	}

	public void setReceivers(List<AddMember> receivers) {
		this.receivers = receivers;
	}

	public MyTask(RemTask remTask, List<AddMember> receivers) {
		super();
		this.remTask = remTask;
		this.receivers = receivers;
	}
	// 获取当前日期
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");	
	String today1 = sdf1.format(new Date());
	private RemPlan remPlan;
	private static boolean isRunning = false;
	@Override
	public void run() {
		if (!isRunning) {
			List<RemTask> tasks = sendService.queryTaskAll();
			sendService.closeDataSource();
			Date now = new Date();// 取时
			Calendar calendar = new GregorianCalendar();
			if (tasks!=null&&tasks.size() > 0) {
				isRunning = true;
				System.out.println("开始执行指定任务");
				//logger.info(sdf.format(new Date())+":开始执行指定任务\n");
				//for(RemTask task:tasks)
				for (int i = 0; i < tasks.size(); i++) {
					RemTask remTask = (RemTask) tasks.get(i);
					receivers=sendService.queryTaskMembers(remTask);
					System.out.println("第几次执行:" + (i + 1));
					//logger.info(sdf.format(new Date())+":第几次执行:" + (i + 1)+"\n");
					Date date = remTask.getRem_first_time();
					if (date != null) {
						date = remTask.getRem_first_time();
					} else {
						date = new Date();
					}
					String ft = sdf.format(date);
					String ft1 = sdf1.format(date);
					
					if (today1.compareTo(ft1) <= 0) {
						if (remTask.getRem_type().equals("0")) {
							// 单次提醒任务
							singleTask(remTask, ft);
						} else if (remTask.getRem_type().equals("1")) {// 周期提醒任务
							cycleTask(now, calendar, remTask, ft);
						}
					} else {
						System.out.println("今天没有提醒任务");
						//logger.info(sdf.format(new Date())+":今天没有提醒任务\n");
					}
					if (i < tasks.size() - 1) {
						System.out.println("上一次任务执行还未结束");
						//logger.info(sdf.format(new Date())+":上一次任务执行还未结束\n");
					}					
				}
				isRunning = false;
				System.out.println("指定任务执行结束");
				//logger.info(sdf.format(new Date())+":指定任务执行结束\n");
			} else {
				System.out.println("无可执行的任务");
				//logger.info(sdf.format(new Date())+":无可执行的任务\n");
			}
		}
		
	}

	private void cycleTask(Date now, Calendar calendar, RemTask remTask,String ft) {
		System.out.println("周期提醒任务开始执行");
		//logger.info(sdf.format(new Date())+":周期提醒任务开始执行\n");
		Date start = remTask.getRem_start_date();
		Date end = remTask.getRem_end_date();
		if (start != null) {
			start = remTask.getRem_start_date();
		} else {
			start = new Date();
		}
		if (end != null) {
			end = remTask.getRem_end_date();
		} else {
			end = new Date();
		}
		String startdate = sdf.format(start);
		String enddate = sdf.format(end);
		String nowtime = sdf.format(new Date());
		Long modify_status_time = end.getTime()+10*60*1000;	//enddate延后10分钟
		// 判断任务是否在有效期内
		if (startdate.compareTo(nowtime) <=0&& nowtime.compareTo(enddate) <=0) {
			plans = this.sendService.queryPlanALL(remPlan,remTask);
			sendService.closeDataSource();
			if (plans!=null&&plans.size() > 0) {
				// 周期性提醒任务处理
				for (int j = 0; j < plans.size(); j++) {
					RemPlan plan = (RemPlan) plans.get(j);
					int cyclenumber = Integer.parseInt(plan.getRem_cycle_number());
					// 周期类型CYCLE_TYPE=0-按天
					if (plan.getCycle_type().equals("0")) {
						
						excuteTaskDay(now, calendar,remTask, ft, enddate, plan,cyclenumber);
					} else if (plan.getCycle_type().equals("1")) {// 周期类型：1-按周 数据处理
						excuteTaskWeek(now, calendar,remTask, enddate, plan,cyclenumber);
					} else if (plan.getCycle_type().equals("2")) {// 周期类型：2-按月 数据处理
						excuteTaskMonth(now, calendar,remTask, ft, enddate, plan,cyclenumber);
					}
				}
			} else {
				System.out.println("该任务对应的REM_PLAN为空：数据异常");
				//logger.info(sdf.format(new Date())+":该任务对应的REM_PLAN为空：数据异常\n");
			}
		} else{
				if(modify_status_time<new Date().getTime()){//结束时间失效10分钟后修改状态为无效
					// 修改状态为无效；
					this.sendService.statusUpdate(remTask);
					sendService.closeDataSource();
					System.out.println("该任务不在有效时间段内，且状态修改为无效");
					//logger.info(sdf.format(new Date())+":该任务不在有效时间段内，且状态修改为无效\n");
				}
				System.out.println("该任务不在有效时间段内");
				//logger.info(sdf.format(new Date())+":该任务不在有效时间段内\n");
			}
			
		}

	private void excuteTaskMonth(Date now, Calendar calendar, RemTask remTask,String ft, String enddate, RemPlan plan, int cyclenumber) {
		String nowtimebf = sdf.format(new Date(System.currentTimeMillis()-30*1000));
		String nowtimeaf = sdf.format(new Date(System.currentTimeMillis()+30*1000));	
		if (nowtimebf.compareTo(ft)<=0&&nowtimeaf.compareTo(ft)>=0) {
			if (plan.getPlan_cycle().equals("20")) {
				giveNotice(remTask);		
				excuteAfterMonth(now,calendar, remTask,enddate,cyclenumber);
				System.out.println("周期提醒成功==20-按月");
				//logger.info(sdf.format(new Date())+":周期提醒成功==20-按月\n");
			}	
		}
	}

	private void excuteTaskWeek(Date now, Calendar calendar, RemTask remTask,String enddate, RemPlan plan, int cyclenumber) {
		// 执行任务
		String nt = sdf.format(plan.getNexttime());
		String nowtimebf = sdf.format(new Date(System.currentTimeMillis()-30*1000));
		String nowtimeaf = sdf.format(new Date(System.currentTimeMillis()+30*1000));	
		System.out.println("nexttime ="+nt +";"+"nowtimebf ="+nowtimebf +";"+"nowtimeaf ="+nowtimeaf +";");
		//logger.info("nexttime ="+nt +";"+"nowtimebf ="+nowtimebf +";"+"nowtimeaf ="+nowtimeaf +";\n");
		if (nowtimebf.compareTo(nt)<=0&&nowtimeaf.compareTo(nt)>=0) {
			System.out.println("当前时间=nexttime");
			//logger.info("当前时间=nexttime\n");
			excuteWeek(remTask,plan);
			// 任务执行后数据处理
			excuteAfterWeek(now, calendar,remTask, enddate, plan,cyclenumber);
			System.out.println("周期提醒成功==2-按周"+plan.getPlan_cycle());
			//logger.info(sdf.format(new Date())+":周期提醒成功==2-按周(11-17)\n");
		} else {
			System.out.println("当前时间不等于nexttime");
			//logger.info(sdf.format(new Date())+":无可执行的任务==按周\n");
		}
	}

	private void excuteTaskDay(Date now, Calendar calendar, RemTask remTask,String ft, String enddate, RemPlan plan, int cyclenumber) {
		String nowtimebf = sdf.format(new Date(System.currentTimeMillis()-30*1000));
		String nowtimeaf = sdf.format(new Date(System.currentTimeMillis()+30*1000));	
		if (nowtimebf.compareTo(ft)<=0&&nowtimeaf.compareTo(ft)>=0) {
			if (plan.getPlan_cycle().equals("00")) {// 计划周期PLAN_CYCLE=00-每天
				this.giveNotice(remTask);
				// 任务执行后数据处理
				excuteAfterDay(now,calendar, remTask,enddate,cyclenumber);
				System.out.println("周期提醒成功==00-每n天");
				//logger.info(sdf.format(new Date())+":周期提醒成功==00-每n天\n");
			} else {// 01=每工作日（周一到周五）
				// 执行任务
				excuteDayWeek(remTask,plan);
				// 任务执行后数据处理
				excuteAfterDayWeek(now,calendar, remTask,enddate); 
				System.out.println("周期提醒成功==01-每工作日");
				//logger.info(sdf.format(new Date())+":周期提醒成功==01-每工作日\n");
			}	
		}else{
			System.out.println("没有类型为【0-按天】的周期任务");
			//logger.info(sdf.format(new Date())+":没有类型为【0-按天】的周期任务\n");
		}
	}
	//单次任务执行
	private void singleTask(RemTask remTask, String ft) {
		String nowtimebf = sdf.format(new Date(System.currentTimeMillis()-30*1000));
		String nowtimeaf = sdf.format(new Date(System.currentTimeMillis()+30*1000));	
		if (nowtimebf.compareTo(ft)<=0&&nowtimeaf.compareTo(ft)>=0) {
			System.out.println("第一次提醒时间为" + ft);
			//logger.info(sdf.format(new Date())+":第一次提醒时间为" + ft+"\n");
			this.giveNotice(remTask);
			// 将已执行过的任务状态修改为无效
			this.sendService.statusUpdate(remTask);
			System.out.println("修改后的状态为"+ remTask.getRem_status());
			//logger.info(sdf.format(new Date())+":修改后的状态为"+ remTask.getRem_status()+"\n");
			System.out.println("单次提醒成功");
			//logger.info(sdf.format(new Date())+":单次提醒成功\n");
			sendService.closeDataSource();
		}else{
			System.out.println("无单次提醒任务");
			//logger.info(sdf.format(new Date())+":无单次提醒任务\n");
		}
	}
	//plan_cycle=11-17 任务执行
	private void excuteWeek(RemTask remTask,RemPlan plan) {
		Calendar nowtime = Calendar.getInstance();	
		int _week = nowtime.get(Calendar.DAY_OF_WEEK) - 1;
		System.out.println("调用周处理方法:"+"_week="+_week);
		//logger.info("调用周处理方法:"+"_week="+_week+"\n");
		if (plan.getPlan_cycle().equals("11")&& (_week == 1)) {
			this.giveNotice(remTask);
		} else if (plan.getPlan_cycle().equals("12")&& (_week == 2)) {
			this.giveNotice(remTask);
		} else if (plan.getPlan_cycle().equals("13")&& (_week == 3)) {
			this.giveNotice(remTask);
		} else if (plan.getPlan_cycle().equals("14")&& (_week == 4)) {
			this.giveNotice(remTask);
		} else if (plan.getPlan_cycle().equals("15")&& (_week == 5)) {
			this.giveNotice(remTask);
		} else if (plan.getPlan_cycle().equals("16")&& (_week == 6)) {
			this.giveNotice(remTask);
		} else if (plan.getPlan_cycle().equals("17")&& (_week == 0)) {
			System.out.println("今天周日，开始调用发邮件方法");
			//logger.info("今天周日，开始调用发邮件方法\n");
			this.giveNotice(remTask);
		}
	}
	//plan_cycle=10（11-15）任务执行
	private void excuteDayWeek(RemTask remTask,RemPlan plan) {
		Calendar nowtime = Calendar.getInstance();	
		int _week = nowtime.get(Calendar.DAY_OF_WEEK) - 1;
		System.out.println("_week======"+_week);
		//logger.info("_week======"+_week+"\n");
		if (_week != 6&& _week != 0) {
			if (plan.getPlan_cycle().equals("11")&& (_week == 1)) {
				this.giveNotice(remTask);
			} else if (plan.getPlan_cycle().equals("12")&& (_week == 2)) {
				this.giveNotice(remTask);
			} else if (plan.getPlan_cycle().equals("13")&& (_week == 3)) {
				this.giveNotice(remTask);
			} else if (plan.getPlan_cycle().equals("14")&& (_week == 4)) {
				this.giveNotice(remTask);
			} else if (plan.getPlan_cycle().equals("15")&& (_week == 5)) {
				this.giveNotice(remTask);
			}
		} else {
			System.out.println("无有效周期提醒任务");
			//logger.info(sdf.format(new Date())+":无有效周期提醒任务\n");
		}
	}
	//plan_cycle=20(每几个月)任务执行完后数据处理
	private void excuteAfterMonth(Date now, Calendar calendar, RemTask remTask,String enddate, int cyclenumber) {
		String today = sdf.format(new Date());
		if (today.compareTo(enddate) < 0) {
			// 修改firsttime为=ft+cyclenumber*month；(先判断newft<=enddate时，才需修改)
			calendar.setTime(now);
			calendar.add(calendar.MONTH,cyclenumber);// 把日期往后增加一天.整数往后推,负数往前移动
			Date rem_first_time = calendar.getTime(); // 这个时间就是日期往后推一天的结果
			this.sendService.firsttimeUpdate(remTask,rem_first_time);
		} else {
			// 修改状态为无效；
			this.sendService.statusUpdate(remTask);
		}
		sendService.closeDataSource();
	}
	 //plan_cycle=11-17(每周几)任务执行完后数据处理
	private void excuteAfterWeek(Date now, Calendar calendar, RemTask remTask,String enddate, RemPlan plan, int cyclenumber) {
		String today = sdf.format(new Date());
		//logger.info("邮件发送成功后数据处理\n");
		if (today.compareTo(enddate) < 0) {
			// 修改firsttime为=nexttime+cyclenumber*week；(先判断newft<=enddate时，才需修改)
			calendar.setTime(now);
			calendar.add(calendar.DATE,1);
			Date tomorrow = calendar.getTime();
			this.sendService.firsttimeUpdate(remTask,tomorrow);
			sendService.closeDataSource();
			calendar.setTime(plan.getNexttime());
			calendar.add(calendar.DATE,cyclenumber * 7);// 把日期往后增加一天.整数往后推,负数往前移动
			Date nexttime = calendar.getTime();
			this.sendService.nexttimeUpdate(plan,nexttime);
			sendService.closeDataSource();
		} else {
			// 修改状态为无效；
			this.sendService.statusUpdate(remTask);
			sendService.closeDataSource();
		}
		
	}
	 //plan_cycle=10(每工作日)任务执行完后数据处理
	private void excuteAfterDayWeek(Date now, Calendar calendar,
			RemTask remTask, String enddate) {
		String today = sdf.format(new Date());
		if (today.compareTo(enddate) < 0) {
			// 修改firsttime为=ft+cyclenumber*day；(先判断newft<=enddate时，才需修改)
			calendar.setTime(now);
			calendar.add(calendar.DATE,1);// 把日期往后增加一天.整数往后推,负数往前移动
			Date rem_first_time = calendar.getTime(); // 这个时间就是日期往后推一天的结果
			this.sendService.firsttimeUpdate(remTask,rem_first_time);
			System.out.println("周期任务修改日期成功");
			//logger.info(sdf.format(new Date())+":周期任务修改日期成功\n");
		} else {
			// 修改状态为无效；
			this.sendService.statusUpdate(remTask);
			System.out.println("修改状态为无效");
			//logger.info(sdf.format(new Date())+":修改状态为无效\n");
		}
		sendService.closeDataSource();
	}
    //plan_cycle=00(每几天)任务执行完后数据处理
	private void excuteAfterDay(Date now, Calendar calendar, RemTask remTask,String enddate, int cyclenumber) {
		String today = sdf.format(new Date());
		if (today.compareTo(enddate) < 0) {
			// 修改firsttime为=ft+cyclenumber*day；(先判断执行时间<=enddate时，才需修改)
			calendar.setTime(now);
			calendar.add(calendar.DATE,cyclenumber);// 把日期往后增加一天.整数往后推,负数往前移动
			Date rem_first_time = calendar.getTime(); // 这个时间就是日期往后推cyclenumber天的结果
			this.sendService.firsttimeUpdate(remTask,rem_first_time);
		} else {
			// 修改状态为无效；
			this.sendService.statusUpdate(remTask);
		}
		sendService.closeDataSource();
	}
	//发送通知
	private void giveNotice(RemTask remTask) {
		System.out.println("正在调用发邮件方法");
		//logger.info("正在调用发邮件方法\n");
		if(remTask.getRem_way().equals("0")){
			System.out.println("开始调用sendEmail");
			//logger.info("开始调用sendEmail\n");
			this.sendEmail(remTask);
		}else if(remTask.getRem_way().equals("1")){
			this.sendMessage(remTask);
		}else if(remTask.getRem_way().equals("0,1")){
			this.sendEmail(remTask);
			this.sendMessage(remTask);
		}
	}
	public void sendEmail(RemTask remTask) {
		System.out.println("开始发送邮件");
		//logger.info(sdf.format(new Date())+":开始发送邮件\n");
		MessageSender sender = new EmailSender();
		sender.send(remTask, receivers);
		System.out.println("邮件已经到达");
		//logger.info(sdf.format(new Date())+":邮件已经到达\n");
	}
	public void sendMessage(RemTask remTask) {
		System.out.println("发送短信");
		//logger.info(sdf.format(new Date())+":发送短信\n");
		
	}
}
